// backend/api/metadata-driven.js
const express = require('express');
const router = express.Router();

// 模拟数据库存储
let dataSources = [
  {
    id: 'sales_data',
    name: '销售数据表',
    tableName: 'sales_records',
    fields: [
      {
        key: 'id',
        label: 'ID',
        type: 'number',
        required: true,
        editable: false,
        searchable: true
      },
      {
        key: 'customerName',
        label: '客户名称',
        type: 'string',
        required: true,
        editable: true,
        searchable: true
      },
      {
        key: 'product',
        label: '产品',
        type: 'string',
        required: true,
        editable: true,
        searchable: true,
        enum: ['产品A', '产品B', '产品C', '产品D']
      },
      {
        key: 'amount',
        label: '金额',
        type: 'number',
        required: true,
        editable: true,
        searchable: true
      },
      {
        key: 'date',
        label: '日期',
        type: 'date',
        required: true,
        editable: true,
        searchable: true
      },
      {
        key: 'status',
        label: '状态',
        type: 'string',
        required: true,
        editable: true,
        searchable: true,
        enum: ['已下单', '已发货', '已完成', '已取消']
      },
      {
        key: 'isVip',
        label: 'VIP客户',
        type: 'boolean',
        required: false,
        editable: true,
        searchable: true
      },
      {
        key: 'notes',
        label: '备注',
        type: 'text',
        required: false,
        editable: true,
        searchable: false
      }
    ]
  }
];

let tableData = [
  {
    id: 1,
    customerName: '张三',
    product: '产品A',
    amount: 1200,
    date: '2023-11-15',
    status: '已完成',
    isVip: true,
    notes: '重要客户'
  },
  {
    id: 2,
    customerName: '李四',
    product: '产品B',
    amount: 800,
    date: '2023-11-16',
    status: '已发货',
    isVip: false,
    notes: ''
  },
  {
    id: 3,
    customerName: '王五',
    product: '产品C',
    amount: 2500,
    date: '2023-11-17',
    status: '已下单',
    isVip: true,
    notes: '大额订单'
  }
];

// 获取所有数据源列表
router.get('/data-sources', (req, res) => {
  res.json({
    code: 200,
    data: dataSources,
    message: '获取数据源列表成功'
  });
});

// 获取特定数据源的元数据
router.get('/data-sources/:id', (req, res) => {
  const dataSource = dataSources.find(ds => ds.id === req.params.id);
  if (!dataSource) {
    return res.status(404).json({
      code: 404,
      message: '数据源不存在'
    });
  }

  res.json({
    code: 200,
    data: dataSource,
    message: '获取数据源元数据成功'
  });
});

// 获取数据表数据（支持分页和筛选）
router.get('/data-sources/:id/data', (req, res) => {
  const { page = 1, limit = 10, ...filters } = req.query;

  // 应用筛选条件
  let filteredData = [...tableData];

  // 根据查询参数筛选数据
  Object.keys(filters).forEach(key => {
    if (key !== 'page' && key !== 'limit') {
      const filterValue = filters[key];
      filteredData = filteredData.filter(item => {
        if (typeof item[key] === 'string') {
          return item[key].includes(filterValue);
        }
        return item[key] == filterValue;
      });
    }
  });

  // 分页处理
  const startIndex = (page - 1) * limit;
  const endIndex = startIndex + parseInt(limit);
  const paginatedData = filteredData.slice(startIndex, endIndex);

  res.json({
    code: 200,
    data: {
      list: paginatedData,
      total: filteredData.length,
      page: parseInt(page),
      limit: parseInt(limit)
    },
    message: '获取数据成功'
  });
});

// 创建新记录
router.post('/data-sources/:id/data', (req, res) => {
  const newData = {
    id: tableData.length > 0 ? Math.max(...tableData.map(d => d.id)) + 1 : 1,
    ...req.body
  };

  tableData.push(newData);

  res.json({
    code: 200,
    data: newData,
    message: '创建数据成功'
  });
});

// 更新记录
router.put('/data-sources/:id/data/:recordId', (req, res) => {
  const recordId = parseInt(req.params.recordId);
  const index = tableData.findIndex(item => item.id === recordId);

  if (index === -1) {
    return res.status(404).json({
      code: 404,
      message: '记录不存在'
    });
  }

  tableData[index] = {
    ...tableData[index],
    ...req.body
  };

  res.json({
    code: 200,
    data: tableData[index],
    message: '更新数据成功'
  });
});

// 删除记录
router.delete('/data-sources/:id/data/:recordId', (req, res) => {
  const recordId = parseInt(req.params.recordId);
  const index = tableData.findIndex(item => item.id === recordId);

  if (index === -1) {
    return res.status(404).json({
      code: 404,
      message: '记录不存在'
    });
  }

  tableData.splice(index, 1);

  res.json({
    code: 200,
    message: '删除数据成功'
  });
});



module.exports = router;
